package com.edais.service.imp.gift;

import com.edais.dao.UserVouchersDao;
import com.edais.domain.User;
import com.edais.domain.UserVouchers;
import com.edais.domain.VouchersRule;
import com.edais.domain.gift.GiftPackageGift;
import com.edais.domain.gift.GiftPackageGiftOrder;
import com.edais.service.GiftExchangeFunction;
import com.edais.service.UserService;
import com.edais.service.gift.GiftPackageGiftOrderService;
import com.edais.util.CommonUtil;
import com.edais.util.Consts;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 代金卷
 * Created by haoyx on 2016/11/10.
 */
@Service("cashCouponImpl")
public class CashCouponImpl implements GiftExchangeFunction {

    private static final Logger logger = Logger.getLogger(CashCouponImpl.class);

    @Autowired
    private UserService userService;

    @Autowired
    private UserVouchersDao userVouchersDao;

    @Autowired
    private GiftPackageGiftOrderService orderService;

    @Override
    @Transactional(propagation= Propagation.REQUIRED,rollbackFor=Exception.class,readOnly=false)
    public Map<String,String> apply(Map<String,Object> params) throws Exception {
        Map<String, String> resMap = new HashMap<String, String>();
        String error = validParams(params);
        if(!StringUtils.isEmpty(error)){
            logger.info(error);
            error = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE,
                    Consts.ErrorMsg.MSG00001,error);
            resMap.put("error",error);
            return resMap;
        }

        //参数获取
        GiftPackageGift giftPackageGift = (GiftPackageGift)params.get("giftPackageGift");
        Long packageOrderId = Long.valueOf(params.get("packageOrderId").toString());
        String userId = params.get("userId").toString();
        String mobile = String.valueOf(params.get("mobile"));
        String vouchersRuleId = String.valueOf(params.get("vouchersRuleId"));
        Integer period = Integer.valueOf(params.get("period").toString());

        final String logInfo = "手续费抵扣卷" + giftPackageGift.getId() + userId + "-";

        logger.info(logInfo+"开始");

        User user = this.userService.selectUser(Long.valueOf(userId),mobile);
        if(null == user){
            logger.info(logInfo+"查询不到此用户");
            error = CommonUtil.setResultStringCn(new HashMap<String, Object>(),Consts.ERROR_CODE,
                    Consts.ErrorMsg.MSG00001,"查询不到此用户");
            resMap.put("error",error);
            return resMap;
        }

        Date nowDate = this.userService.getSysdate();

        //生成订单
        GiftPackageGiftOrder order = this.orderService.generateOrder(logInfo,packageOrderId,user,giftPackageGift,nowDate);

        //生成代金券
        this.insertVouchers(logInfo,userId,vouchersRuleId,nowDate,period);

        logger.info(logInfo+"成功");

        return resMap;
    }

    /**
     * 生成代金券
     * @param loginfo       日志头
     * @param userId        用户id
     * @param voucherId  规则ID
     * @param nowDate   数据库当前时间
     * @param period        过期时长
     */
    private void insertVouchers(String loginfo,String userId,String voucherId,Date nowDate,Integer period) {
        try {

            Map<String, Object> paramsMap=new HashMap<String, Object>();
            paramsMap.put("voucherId", voucherId);
            VouchersRule vouchersRule = userVouchersDao.queryVouchersRuleById(paramsMap);
            UserVouchers userVouchers = new UserVouchers();
            userVouchers.setUser_id(Long.valueOf(userId));
            userVouchers.setVoucher_type_id(Long.valueOf(voucherId));

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            nowDate = sdf.parse(sdf.format(nowDate));
            Calendar cal = Calendar.getInstance();
            cal.setTime(nowDate);
            cal.add(Calendar.DATE, period - 1);
            userVouchers.setEnddate(cal.getTime());

            userVouchers.setStartdate(nowDate);
            userVouchers.setVoucher_amount(vouchersRule.getVoucher_amount());
            userVouchers.setInvestment_amount(vouchersRule.getInvestment_amount());
            userVouchers.setSource("13");
            userVouchers.setGift_staff(userId);
            userVouchers.setCreate_time(new Date());
            userVouchers.setStatus("0");
            userVouchers.setCreate_per(userId);
            userVouchersDao.addUserVouchers(userVouchers);
        } catch (Exception e) {
            logger.error(loginfo+"生成代金券错误："+e);
        }
    }

    @Override
    public String validParams(Map<String,Object> params) {
        if(null == params || params.isEmpty())
            return "参数列表不能为空";
        if(!params.containsKey("giftPackageGift") || null == params.get("giftPackageGift"))
            return "参数giftPackageGift不能为空";
        if(!params.containsKey("packageOrderId")  || StringUtils.isEmpty(params.get("packageOrderId")))
            return "参数packageOrderId不能为空";
        if(!params.containsKey("userId")  || StringUtils.isEmpty(params.get("userId")))
            return "参数userId不能为空";
        if(!params.containsKey("mobile")  || StringUtils.isEmpty(params.get("mobile")))
            return "参数mobile不能为空";
        if(!params.containsKey("vouchersRuleId")  || StringUtils.isEmpty(params.get("vouchersRuleId")))
            return "参数vouchersRuleId不能为空";
        if(!params.containsKey("period")  || StringUtils.isEmpty(params.get("period")))
            return "参数period不能为空";
        return null;
    }


}
